<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/11/11
 * Time: 14:52
 */

namespace app\api\command\spider;

use think\console\Command;

class SpiderBase extends Command
{

    protected $imageBaseDir='/www/wwwroot/kanpuba.com/public/';
    protected $uploads = 'uploads';
    public $domain="http://182.92.125.214";
    /**
     * 返回抓取成功的图片路径
     * @param $url  要抓取的图片
     * @param string $dir 图片存放路径
     * @return string
     */
    protected function _downImage($url,$dir='default'){
        if($url != 'https://www.gdwxcn.com/images/xiaoshuo/nopic.jpg'){
            $filename = md5($url).".jpg";
            $save_dir = $this->imageBaseDir.$this->uploads."/".$dir."/";
            if(!is_dir($save_dir)){
                mkdirs($save_dir);
            }
            $rs = $this->_base_getImage($url,$save_dir,$filename);
//            print_r($rs);exit;
            $imgurl = "/".$this->uploads."/".$dir."/".$filename;
        } else {
            $imgurl = '';
        }
        return $imgurl;

    }

    protected function _getContentImg($content){
        $preg = '/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/';
        preg_match_all($preg, $content, $match);
//        print_r($match);exit;
        $count = count($match[1]);
        $filepaths = array();
        if ($count > 0) {
            for ($i = 0; $i < $count; $i++) {
                if ($i != $count - 1) {
                    $filepaths[] = $match[1][$i];
                } else {
                    $filepaths[] = $match[1][$i];
                }
            }
        }

        return $filepaths;
    }

    /*
     * 功能：php完美实现下载远程图片保存到本地 ，当前仅支持单个图片下载
     * 参数：文件url,保存文件目录,保存文件名称，使用的下载方式
     * 当保存文件名称为空时则使用远程文件原来的名称
     */

    protected function _base_getImage($url, $save_dir = '', $filename = '', $type = 0) {
//        echo $url;exit;
//        echo $filename;exit;
//        $url = "http:".$url;
        $url = "http:".trim($url,'http:');
        if (trim($url) == '') {
            return array('code' => 1, 'error' => '文件url不合法');
        }

        if($url){

        }

        if (trim($save_dir) == '') {
            $save_dir = './';
        }
        if (trim($filename) == '') {//保存文件名
            $ext = strrchr($url, '.');
            if ($ext != '.gif' && $ext != '.jpg' && $ext != '.png') {
                return array('code' => 3, 'error' => '文件类型不合法');
            }
            $filename = substr($url, strripos($url, "/") + 1);
        }

        if (0 !== strrpos($save_dir, '/')) {
            $save_dir.='/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return array('code' => 5, 'error' => '创建文件失败');
        }
        //获取远程文件所采用的方法
        if ($type) {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $img = curl_exec($ch);
            curl_close($ch);
        } else {
            // echo "sd";exit;
            ob_start();
            @$rs = readfile($url);
//             var_dump($rs);exit;
            $img = ob_get_contents();
            ob_end_clean();
        }
        $size = strlen($img);

//         echo $size;exit;
        //文件大小
//        echo $save_dir.$filename;exit;
        if(empty($size)){
            return array('code' => 1, 'error' => "文件" . $filename . "为空，下载失败！");
        } else {
           $fp2 = @fopen($save_dir . $filename, 'a');
            fwrite($fp2, $img);
            fclose($fp2);
    //        print_r($filename);exit;
            unset($img, $url);
            // if($size > 1048576){ //大于1M则删除
            //     unlink($save_dir.$filename);
            // }
            return array('code' => 0, 'error' => "文件" . $filename . "保存成功"); 
        }
        
    }


    protected function _getCurl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $result = curl_exec($ch);
        if (!$result) {
            //输出错误信息
            //trigger_error(curl_error($ch));
            return false;
        }
        curl_close($ch);
        return $result;
    }

    protected function _get_url($url) {
        $ifpost = 0;
        $datafields = '';
        $cookiefile = '';
        $v = false;
        //构造随机ip
        $ip_long = array(
            array('607649792', '608174079'), //36.56.0.0-36.63.255.255
            array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
            array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
            array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
            array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
            array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
            array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
            array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
            array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
            array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
        );
        $rand_key = mt_rand(0, 9);
        $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
//模拟http请求header头
        $header = array("Connection: Keep-Alive", "Accept: text/html, application/xhtml+xml, */*", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3", "User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)", 'CLIENT-IP:' . $ip, 'X-FORWARDED-FOR:' . $ip);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, $v);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $ifpost && curl_setopt($ch, CURLOPT_POST, $ifpost);
        $ifpost && curl_setopt($ch, CURLOPT_POSTFIELDS, $datafields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $cookiefile && curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        $cookiefile && curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //允许执行的最长秒数
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $ok = curl_exec($ch);


        curl_close($ch);
        unset($ch);
        return $ok;
    }

    //过滤空格
    protected function myTrim($str) {
        $search = array(" ", "　", "\n", "\r", "\t", "<br>","<br >"," <br/>","<br />","    ");
        $replace = array("", "", "", "", "", "","","","","");
        return str_replace($search, $replace, $str);
    }
    protected function ticheck(){
        $nowH = (int)date("H",time());
        if($nowH < 8 || $nowH > 18){
            echo "不在提交时间内！";exit;
        }
    }
}